package com.example.administrator.college02.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.Transformation;

import com.example.administrator.college02.R;

import java.io.InputStream;

public class KyTile extends View implements OnGestureListener {
	private GestureDetector mGestureDetector;
	protected OnClickListener onClickListener;
	//属性
	private int icon;
	private int changedSize;
	private int cornerRadius;
	//运行时参数
	private int iconWidth;//图片的宽度，会根据触碰变化
	
	public KyTile(Context context) {
		super(context);
		mGestureDetector = new GestureDetector(this);
		this.changedSize = dip2px(this.getContext(), 6);
		this.cornerRadius = dip2px(this.getContext(), 4);
	}
	public KyTile(Context context, AttributeSet attrs) {
		super(context, attrs);
		mGestureDetector = new GestureDetector(this);
		TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.kytile);
		icon = a.getResourceId(R.styleable.kytile_icon, 0);
		changedSize = (int)a.getDimension(R.styleable.kytile_changedSize, dip2px(this.getContext(), 6));
		cornerRadius = (int)a.getDimension(R.styleable.kytile_cornerRadius, dip2px(this.getContext(), 4));
	}
	@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		int maxWidth = MeasureSpec.getSize(widthMeasureSpec);
		int maxHeight = MeasureSpec.getSize(heightMeasureSpec);
		int defaultWidth = 0;
		int defaultHeight = 0;
		int specMode = MeasureSpec.getMode(widthMeasureSpec);
		if (specMode == MeasureSpec.EXACTLY)
			defaultWidth = MeasureSpec.getSize(widthMeasureSpec);
		specMode = MeasureSpec.getMode(heightMeasureSpec);
		if (specMode == MeasureSpec.EXACTLY)
			defaultHeight = MeasureSpec.getSize(heightMeasureSpec);
		
		if(defaultWidth != 0 && defaultHeight != 0){//有具体的宽高值
			setMeasuredDimension(defaultWidth, defaultHeight);
			return ;
		}
		Bitmap bitmap = loadIcon();
		if(bitmap == null){//未设置图片
		    setMeasuredDimension(0, 0);
		    bitmap.recycle();
		    return ;
	    }
		if(defaultWidth == 0 && defaultHeight == 0){//都未设置具体的宽高	    	
			setMeasuredDimension(Math.min(bitmap.getWidth(), maxWidth), Math.min(bitmap.getHeight(), maxHeight));
			bitmap.recycle();
			return ;
		}
		if(defaultWidth == 0 && defaultHeight != 0){//宽度未设置
			bitmap = resizeBitmap_height(bitmap, defaultHeight) ;
			setMeasuredDimension(Math.min(bitmap.getWidth(), maxWidth), defaultHeight);
			bitmap.recycle();
			return ;
		}
		if(defaultWidth != 0 && defaultHeight == 0){//高度未设置
			bitmap = resizeBitmap_width(bitmap, defaultWidth) ;
			setMeasuredDimension(defaultWidth, Math.min(bitmap.getHeight(), maxHeight));
			bitmap.recycle();
			return ;
		}
    }	
    /**
     * 开始画
     */
    @Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
        //canvas.drawColor(0xFF00FF33);
		drawIcon(canvas);
	}
    /**
	 * 画图标
	 */
	private void drawIcon(Canvas canvas){
		//创建bitmap
		Bitmap bitmap = loadIcon();
		if(bitmap == null)
			return ;
		
		this.iconWidth = this.iconWidth == 0 ? this.getWidth() : this.iconWidth;
		//缩放图片
		int iconHeight = (int)(((float)this.iconWidth)/this.getWidth() * this.getHeight());
		bitmap = resizeBitmap(bitmap, this.iconWidth, iconHeight);
		//生成圆角的		
		bitmap = createCornerImage(bitmap);  
		canvas.drawBitmap(bitmap, this.getWidth()/2 - bitmap.getWidth()/2, this.getHeight()/2 - bitmap.getHeight()/2, null);		
	}
    /** 
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素) 
     */  
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;  
        return (int) (dpValue * scale + 0.5f);  
    }
    /**
     * 加载icon
     */
    private Bitmap loadIcon(){
    	try {
			if(this.icon == 0)
				return null;
			BitmapFactory.Options opt = new BitmapFactory.Options();
			opt.inPreferredConfig = Bitmap.Config.ARGB_4444;
			InputStream is = getResources().openRawResource(this.icon);
			Bitmap bitmap =  BitmapFactory.decodeStream(is,null,opt);
			return bitmap;
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return null;
    }
	/**
	 * 调整图片大小
	 */
	public static Bitmap resizeBitmap(Bitmap bitmap, int newWidth, int newHeight) {
        if (bitmap != null) {
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            float scaleWidth = ((float) newWidth) / width;
            float scaleHeight = ((float) newHeight) / height;
            Matrix matrix = new Matrix();
            matrix.postScale(scaleWidth, scaleHeight);
            Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
            //bitmap.recycle();
            return resizedBitmap;
        } else {
            return null;
        }
    }
	/**
	 * 调整图片大小
	 */
	public static Bitmap resizeBitmap_width(Bitmap bitmap, int newWidth) {
        if (bitmap != null) {
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            float scaleSize = ((float) newWidth) / width;
            Matrix matrix = new Matrix();
            matrix.postScale(scaleSize, scaleSize);
            Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
            //bitmap.recycle();
            return resizedBitmap;
        } else {
            return null;
        }
    }
	/**
	 * 调整图片大小
	 */
	public static Bitmap resizeBitmap_height(Bitmap bitmap, int newHeight) {
        if (bitmap != null) {
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            float scaleSize = ((float) newHeight) / height;
            Matrix matrix = new Matrix();
            matrix.postScale(scaleSize, scaleSize);
            Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
            //bitmap.recycle();
            return resizedBitmap;
        } else {
            return null;
        }
    }
	/**
	 * 生成圆角的bitmap
	 */
	private Bitmap createCornerImage(Bitmap source) {
		final Paint paint = new Paint();
        paint.setAntiAlias(true);  
        Bitmap target = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Config.ARGB_4444);
        Canvas canvas = new Canvas(target);
        RectF rect = new RectF(0, 0, source.getWidth(), source.getHeight());
        canvas.drawRoundRect(rect, this.cornerRadius, this.cornerRadius, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(source, 0, 0, paint); 
        //source.recycle();
        return target;  
	}
	/**
	 * 触碰事件
	 */
	@Override
    public boolean onTouchEvent(MotionEvent event) {
    	try {
    		mGestureDetector.onTouchEvent(event);
    		if(event.getAction() == MotionEvent.ACTION_UP){
    			upEventHandler();
    		}
		} catch (Exception e) {
			e.printStackTrace();
		}
        return true;
    }
	//手势监听
	@Override
	public boolean onDown(MotionEvent event) {
		downEventHandler();
		return true;
	}
	@Override
	public boolean onFling(MotionEvent event1, MotionEvent event2, float arg2, float arg3) {
		return true;
	}
	@Override
	public void onLongPress(MotionEvent event) {
	}
	@Override
	public boolean onScroll(MotionEvent event1, MotionEvent event2, float arg2, float arg3) {
		return true;
	}
	@Override
	public void onShowPress(MotionEvent event) {
	}
	@Override
	public boolean onSingleTapUp(MotionEvent event) {
		clickEventHandler();
		return true;
	}
	/**
	 * 手指按下处理
	 */
	private void downEventHandler(){
		SuoxiaoAnimation animation = new SuoxiaoAnimation(this.getWidth());
        animation.setInterpolator(new LinearInterpolator());
        animation.setDuration(150);
        this.iconWidth = this.getWidth();
        this.startAnimation(animation);
	}
	/**
	 * up事件处理
	 */
	private void upEventHandler(){
		FangdaAnimation animation = new FangdaAnimation(this.getWidth());
        animation.setInterpolator(new LinearInterpolator());
        animation.setDuration(150);
        this.startAnimation(animation);  
	}	
	/**
	 * 单击事件
	 */
	private void clickEventHandler(){
		if(this.onClickListener != null)
			this.onClickListener.onClick(this);
	}
	/**
	 * 缩小动画
	 */
	private  class SuoxiaoAnimation  extends Animation {
		private int widgetWidth;
		public SuoxiaoAnimation(int widgetWidth){
			this.widgetWidth = widgetWidth;
		}
		@Override
		protected void applyTransformation(float interpolatedTime, Transformation t) {
			if(interpolatedTime<=1){				
				iconWidth = (int)(widgetWidth - interpolatedTime*changedSize);
				invalidate();
			}
		}		
	}
	/**
	 * 放大动画
	 */
	private  class FangdaAnimation  extends Animation {
		private int widgetWidth;
		public FangdaAnimation(int widgetWidth){
			this.widgetWidth = widgetWidth;
		}
		@Override
		protected void applyTransformation(float interpolatedTime, Transformation t) {
			if(interpolatedTime<=1){				
				iconWidth = (int)(widgetWidth - (1-interpolatedTime)*changedSize);
				invalidate();
			}
		}		
	}
	
	
	
	
	

    public void setOnClickListener(OnClickListener onClickListener) {
		this.onClickListener = onClickListener;
	}

	public int getIcon() {
		return icon;
	}
	public void setIcon(int icon) {
		this.icon = icon;
	}
	public int getChangedSize() {
		return changedSize;
	}
	public void setChangedSize(int changedSize) {
		this.changedSize = changedSize;
	}
	public int getCornerRadius() {
		return cornerRadius;
	}
	public void setCornerRadius(int cornerRadius) {
		this.cornerRadius = cornerRadius;
	}
}
